﻿using Aker.DevTeam;
using Aker.Iplik;
using Aker.MainForms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace Aker.Uretim
{
    public partial class YeniSiparis : XForm
    {
        int SiparisTipi = -1;
        int POrderId = -1;
        AkerDB.POrderRow po = null;

        AkerDB.POrderDataTable dtMaster = new AkerDB.POrderDataTable();
        AkerDB.POrderLinesDataTable dtLines = new AkerDB.POrderLinesDataTable();

        List<int> selectedIds;

        string[] editAbleColumns = null;
        string[] orderedColumns = null;

        public YeniSiparis(List<int> productIds)
        {
            InitializeComponent();
            SiparisTipi = 1;
            selectedIds = productIds;

            InitSiparisTipi();
        }

        private void InitSiparisTipi()
        {
            if (SiparisTipi == 1)
            {
                editAbleColumns = new string[] { "Price", "KG", "Meters", "Yards", "Notes", "ETA", "MusteriKodu" };
                orderedColumns = new string[] { "Görsel", "Article", "MusteriKodu", "Design", "Weight", "Width", "Composition", "Meters", "Yards", "KG", "Price", "PriceFOB", "Notes", "LineTotal", "ETA" };
            }
            else if (SiparisTipi == 2)
            {
                //dtLines.Columns.Add("Iplik", typeof(string));
                editAbleColumns = new string[] { "Price", "KG", "Notes", "ETA", "BirimAdet" };
                orderedColumns = new string[] { "Grup", "BirimAdet", "KG", "Price", "PriceFOB", "Notes", "LineTotal", "ETA" };
            }
        }

        public YeniSiparis(int pOrderId)
        {
            InitializeComponent();
            POrderId = pOrderId;
        }

        DataTable dtIplik = null;
        public YeniSiparis(DataTable dtIplik)
        {
            InitializeComponent();
            this.dtIplik = dtIplik;

            SiparisTipi = 2;
            InitSiparisTipi();

        }

        private void NewOrder_Load(object sender, EventArgs e)
        {
            if (SiparisTipi == 1)
                this.Text = "Yeni Üretim Siparişi";
            else if (SiparisTipi == 2)
                this.Text = "Yeni İplik Siparişi";
            gcProduct.Enabled = false;
            if (Data.IsLookupInitialized)
                Data_LookupInitialized();
            else
                Data.LookupInitialized += Data_LookupInitialized;

        }

        void Data_LookupInitialized()
        {
            cmbHafta.SelectedIndex = 0;

            if (SiparisTipi == 1)
                deETA.EditValue = DateTime.Now.AddDays(7);
            else
                deETA.EditValue = DateTime.Now;

            Data.TAM.AcentaTableAdapter.Fill(Data.DB.Acenta);

            RepositoryItemGridLookUpEdit gle = Utility.GetAutoCompGLE(Data.DB.Customer, "Brand", "CustomerId");
            gle.View.EnableComplexFiltering("Brand");
            gle.View.ShowingEditor += View_ShowingEditor;
            gle.Popup += gle_Popup;
            gleMusteri.Properties.Assign(gle);


            gle = Utility.GetAutoCompGLE(Data.DB.Customer, "Brand", "CustomerId");
            gle.View.EnableComplexFiltering("Brand");
            gle.Popup += gle_Popup;
            gleFaturaMusterisi.Properties.Assign(gle);

            gle = Utility.GetAutoCompGLE(Data.DB.Customer, "Brand", "CustomerId");
            gle.View.EnableComplexFiltering("Brand");
            gle.Popup += gle_Popup;
            gleTeslimatMusterisi.Properties.Assign(gle);

            gle = Utility.GetAutoCompGLE(Data.DB.Acenta, "Acenta", "AcentaId");
            gle.View.EnableComplexFiltering("Acenta");
            gle.Popup += gle_PopupAcenta;
            gleAcenta.Properties.Assign(gle);



            gvLines.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;
            dtLines.Columns.Add("LineTotal", typeof(decimal), "(isnull(Meters,0) + isnull(KG,0)) * Price");


            if (POrderId < 0)
            {
                po = dtMaster.NewPOrderRow();

                if (SiparisTipi == 1)
                {
                    foreach (string col in Data.ProductDetails)
                        dtLines.Columns.Add(col, typeof(string));

                    foreach (int id in selectedIds)
                        AddProduct(id);

                }

                else if (SiparisTipi == 2)
                {
                    dtLines.Columns.Add("Iplik", typeof(string));
                    AddIplik();
                }


                cmbParabirimi.SelectedIndex = 0;
                cmbOdemeSekli.SelectedIndex = 0;
                cmbTeslimatSekli.SelectedIndex = 0;

                gleMusteri.EditValue = 1;
            }
            else
            {
                btnPrint.Enabled = true;
                btnOrder.Text = "Siparişi Güncelle";

                DataSet ds = Data.DM.ExecuteDataSet("GetPOrder", POrderId);
                dtMaster.Clear();
                dtMaster.AcceptChanges();

                dtLines.Clear();
                dtLines.AcceptChanges();
                dtMaster.Clear();
                dtMaster.AcceptChanges();

                dtMaster.Merge(ds.Tables[0]);
                dtLines.Merge(ds.Tables[1]);

                SiparisTipi = dtMaster.Rows[0]["SiparisTipi"].ToIntNN();

                InitSiparisTipi();

                if (SiparisTipi == 1)
                {
                    foreach (string col in Data.ProductDetails)
                        dtLines.Columns.Add(col, typeof(string));

                    FillProductDetail();
                }

                po = dtMaster.FindByPOrderId(POrderId);

                gleMusteri.EditValue = po.CustomerId;

                if (!po.IsContactNull())
                    txtYetkili.Text = po.Contact.ToStringNN();

                if (!po.IsCustomerOrderNoNull())
                    txtMusteriSipNo.Text = po.CustomerOrderNo;

                if (!po.IsDeliveryCustomerIdNull())
                    gleTeslimatMusterisi.EditValue = po.DeliveryCustomerId;

                if (!po.IsDeliveryCustomerLocationNull())
                    txtTeslimatMusterisiLokosyon.Text = po.DeliveryCustomerLocation;

                if (!po.IsInvoiceCustomerIdNull())
                    gleFaturaMusterisi.EditValue = po.InvoiceCustomerId;

                if (!po.IsAcentaIdNull())
                    gleAcenta.EditValue = po.AcentaId;

                cmbOdemeSekli.SelectedIndex = po.PaymentTypeId - 1;
                cmbTeslimatSekli.SelectedIndex = po.TeslimatSekliId - 1;

                if (!po.IsDeliveryLocationNull())
                    txtTeslimatLokosyon.Text = po.DeliveryLocation;

                cmbParabirimi.SelectedIndex = po.CurrencyId - 1;

                if (!po.IsNotesNull())
                    txtNotes.Text = po.Notes.ToStringNN();

                cmbDil.SelectedIndex = po.LangId - 1;

                if (!po.IsOdemeNotuNull())
                    txtOdemeNotu.Text = po.OdemeNotu.ToStringNN();

                if (!po.IsVadeNull())
                {
                    for (int i = 0; i < cmbVade.Properties.Items.Count; i++)
                        if (cmbVade.Properties.Items[i].ToString() == po.Vade.ToString() + " gün")
                        {
                            cmbVade.SelectedIndex = i;
                            break;
                        }
                }
            }

            gvLines.Init(dtLines);

            GridColumn gc = new GridColumn();
            gc.Name = "Görsel";
            gc.Caption = "";
            gc.FieldName = "Görsel";
            gc.VisibleIndex = 0;
            gvLines.Columns.Add(gc);

            gvLines.SetVisibleIndex(orderedColumns);

            //if (SiparisTipi == 1)
            gvLines.SetCaptions("Article:Baz Artikel", "MusteriKodu:Müşteri Kodu", "Design:Desen", "Weight:Ağırlık", "Width:En", "BirimAdet:Adet",
                                "Composition:Karışım", "Meters:Metre", "Yards:Yard", "Price:Fiyat", "PriceFOB:Fiyat (FOB)", "Notes:Not", "LineTotal:Toplam");

            gvLines.AddSummary("LineTotal");
            gvLines.MakeReadOnly(editAbleColumns);
            gvLines.RowCellStyle += gvLines_RowCellStyle;

            if (SiparisTipi == 1)
                gvLines.FormatAsNumber("Price", "KG", "Meters", "Yards", "LineTotal");
            else if (SiparisTipi == 2)
                gvLines.FormatAsNumber("Price", "KG", "LineTotal");

            BestFit();

            GridMenu gmLines = GridManager.GetManager(gvLines).GridMenu;

            if (SiparisTipi == 1)
                gmLines.AddMenu("Artikel ekle", AddProductManual_Click);
            else if (SiparisTipi == 2)
                gmLines.AddMenu("Kopyalanan iplikleri ekle", AddIplikManual_Click);

            gmLines.AddMenu("Seçili satırları sil", DeleteOrderLines, true);

            gvLines.CalcRowHeight += gvLines_CalcRowHeight;
            gvLines.RowCellClick += gvLines_RowCellClick;
            gvLines.CustomDrawCell += gvLines_CustomDrawCell;
            gvLines.MouseMove += gvLines_MouseMove;
            BarcodeRead += Orders_BarcodeRead;

            gleMusteri.EditValueChanged += gleMusteri_EditValueChanged;
            gcProduct.Enabled = true;
        }

        private void gle_PopupAcenta(object sender, System.EventArgs e)
        {
            GridLookUpEdit gle = sender as GridLookUpEdit;
            gle.Properties.View.FocusedColumn = gle.Properties.View.Columns["Acenta"];
            gle.Properties.View.FocusedRowHandle = GridControl.AutoFilterRowHandle;
        }

        void gle_Popup(object sender, System.EventArgs e)
        {
            GridLookUpEdit gle = sender as GridLookUpEdit;
            gle.Properties.View.FocusedColumn = gle.Properties.View.Columns["Brand"];
            gle.Properties.View.FocusedRowHandle = GridControl.AutoFilterRowHandle;
        }

        void View_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            GridView gv = sender as GridView;


        }

        private void AddIplikManual_Click(object sender, EventArgs e)
        {
            foreach (DataRow dr in Iplikler.KopyalanmisIplikler.Rows)
            {
                string grupKodu = dr["GrupKodu"].ToStringNN();
                if (dtLines.Select("GrupKodu='" + grupKodu + "'").Length == 0)
                    AddIplik(dr);
            }
        }

        private void AddIplik()
        {
            foreach (DataRow dr in dtIplik.Rows)
            {
                string grupKodu = dr["GrupKodu"].ToStringNN();
                if (dtLines.Select("GrupKodu='" + grupKodu + "'").Length == 0)
                    AddIplik(dr);
            }
        }

        private void AddIplik(DataRow dr)
        {
            AkerDB.POrderLinesRow pod = dtLines.NewPOrderLinesRow();
            (pod as DataRow)["Grup"] = dr["Grup"].ToStringNN();
            pod.GrupKodu = dr["GrupKodu"].ToStringNN();
            pod.POrderId = po.POrderId;
            pod.ETA = deETA.DateTime;
            dtLines.AddPOrderLinesRow(pod);
        }

        void gvLines_MouseMove(object sender, MouseEventArgs e)
        {
            GridHitInfo hitInfo = gvLines.CalcHitInfo(new Point(e.X, e.Y));

            if (hitInfo.InRowCell && hitInfo.Column.FieldName == "Görsel" && hitInfo.RowHandle > -1)
                gvLines.GridControl.Cursor = Cursors.Hand;
            else
                gvLines.GridControl.Cursor = Cursors.Default;
        }

        void gvLines_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1 && editAbleColumns.Contains(e.Column.FieldName))
                e.Appearance.BackColor = Color.LightYellow;
        }

        private void gvLines_CalcRowHeight(object sender, RowHeightEventArgs e)
        {
            if (!gvLines.IsFilterRow(e.RowHandle))
                e.RowHeight = 50;
        }

        private void gvLines_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e)
        {
            if (e.Column.FieldName == "Görsel" && e.RowHandle > -1)
            {
                int bazProductId = gvLines.GetRowCellValue(e.RowHandle, "BazProductId").ToIntNN();

                if (bazProductId > -1)
                {
                    AkerDB.ProductRow pr = Data.DB.Product.FindByProductId(bazProductId);

                    if (!pr.IsThumbnailNull())
                    {
                        MemoryStream ms = new MemoryStream(pr.Thumbnail);
                        e.Graphics.DrawImage(Image.FromStream(ms), e.Bounds.X, e.Bounds.Y);
                        e.Handled = true;
                    }
                }
            }
        }

        private void gvLines_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.Column.FieldName == "Görsel")
            {
                int bazProductId = gvLines.GetFocusedRowCellValue("BazProductId").ToIntNN();
                if (bazProductId > -1)
                {
                    AkerDB.ProductRow pr = Data.DB.Product.FindByProductId(bazProductId);

                    if (!pr.IsThumbnailNull())
                    {
                        ImageViewer iv = new ImageViewer(bazProductId);
                        iv.ShowDialog();
                    }
                }
            }
        }

        private void cmbCurrency_SelectedIndexChanged(object sender, EventArgs e)
        {
            FillProductDetail();
        }

        private void FillProductDetail()
        {
            foreach (AkerDB.POrderLinesRow ol in dtLines.Rows)
                FillProductDetail(ol);

            UpdateTotal();
        }

        private void UpdateTotal()
        {
            decimal total = dtLines.Compute("sum(LineTotal)", "").ToDecimalNN();
            string val = total.ToString("n2") + " " + cmbParabirimi.SelectedItem.ToStringNN();
            lblTotal.Text = val;
        }

        private void FillProductDetail(AkerDB.POrderLinesRow ol)
        {
            int bazProductId = ol["BazProductId"].ToIntNN();
            if (bazProductId > -1)
            {
                DataRow pr = Data.DB.Product.Select("ProductId = " + bazProductId)[0];

                foreach (string col in Data.ProductDetails)
                {
                    if (pr != null)
                        ol[col] = pr[col];
                }

                if (POrderId < 0)
                {
                    //if (cmbParabirimi.SelectedIndex == 0)
                    //    if (pr["PriceDollar"] != DBNull.Value)
                    //        ol.Price = (decimal)pr["PriceDollar"];
                    //    else
                    //        ol.Price = 0;
                    //else if (pr["PriceEuro"] != DBNull.Value)
                    //    ol.Price = (decimal)pr["PriceEuro"];
                    //else
                    //    ol.Price = 0;
                }
            }
        }
        decimal yard = 0;
        private void gvProduct_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            gvLines.EndEditing();

            if (e.Column.FieldName == "Meters" && e.Value.ToIntNN() > 0 && gvLines.GetRowCellValue(e.RowHandle, "KG").ToIntNN() > 0)
            {
                gvLines.SetRowCellValue(e.RowHandle, "Meters", null);
            }
            if (e.Column.FieldName == "KG" && e.Value.ToIntNN() > 0 && gvLines.GetRowCellValue(e.RowHandle, "Meters").ToIntNN() > 0)
            {
                gvLines.SetRowCellValue(e.RowHandle, "KG", null);
            }
            if (e.Column.FieldName == "Yards" && e.Value.ToIntNN() > 0 && gvLines.GetRowCellValue(e.RowHandle, "KG").ToIntNN() > 0)
            {
                gvLines.SetRowCellValue(e.RowHandle, "Yards", null);
            }

            if (e.Column.FieldName == "Yards")
            {
                if (e.Value.ToIntNN() > 0)
                {
                    yard = (gvLines.GetRowCellValue(e.RowHandle, "Yards").ToIntNN() * 0.9144).ToDecimalNN();
                    if (yard > 0)
                        gvLines.SetRowCellValue(e.RowHandle, "Meters", yard);

                    gvLines.Columns["Meters"].OptionsColumn.AllowEdit = false;
                }
                else
                    gvLines.Columns["Meters"].OptionsColumn.AllowEdit = true;
            }

            if (e.Column.FieldName == "Meters")
            {
                if (e.Value.ToIntNN() > 0 && e.Value.ToDecimalNN() != yard)
                    gvLines.Columns["Yards"].OptionsColumn.AllowEdit = false;
                else
                    gvLines.Columns["Yards"].OptionsColumn.AllowEdit = true;
            }

            UpdateTotal();

            BestFit();
        }

        private void BestFit()
        {
            gvLines.BestFitColumns();
            gvLines.Columns["Görsel"].Width = 52;
        }

        private void btnOrder_Click(object sender, EventArgs e)
        {
            po.CustomerId = gleMusteri.EditValue.ToIntNN();

            if (txtYetkili.Text != "")
                po.Contact = txtYetkili.Text;
            else
                po.SetContactNull();

            if (txtMusteriSipNo.Text != "")
                po.CustomerOrderNo = txtMusteriSipNo.Text;
            else
                po.SetCustomerOrderNoNull();

            if (gleTeslimatMusterisi.EditValue.ToIntNN() != -1)
                po.DeliveryCustomerId = gleTeslimatMusterisi.EditValue.ToIntNN();
            else
                po.SetDeliveryCustomerIdNull();

            if (txtTeslimatMusterisiLokosyon.Text != "")
                po.DeliveryCustomerLocation = txtTeslimatMusterisiLokosyon.Text;
            else
                po.SetDeliveryCustomerLocationNull();

            if (gleFaturaMusterisi.EditValue.ToIntNN() != -1)
                po.InvoiceCustomerId = gleFaturaMusterisi.EditValue.ToIntNN();
            else
                po.SetInvoiceCustomerIdNull();

            if (gleAcenta.EditValue.ToIntNN() != -1)
                po.AcentaId = gleAcenta.EditValue.ToIntNN();
            else
                po.SetAcentaIdNull();


            po.PaymentTypeId = cmbOdemeSekli.SelectedIndex + 1;

            po.TeslimatSekliId = cmbTeslimatSekli.SelectedIndex + 1;

            if (txtTeslimatLokosyon.Text != "")
                po.DeliveryLocation = txtTeslimatLokosyon.Text;
            else
                po.SetDeliveryLocationNull();

            po.CurrencyId = cmbParabirimi.SelectedIndex + 1;

            if (txtNotes.Text != "")
                po.Notes = txtNotes.Text;
            else
                po.SetNotesNull();

            if (POrderId < 0)
            {
                po.CreatorId = AppSession.UserInfo.UserId;
                po.OrderDate = DateTime.Now;
            }


            po.LangId = cmbDil.SelectedIndex + 1;

            if (cmbVade.SelectedIndex > 0)
                po.Vade = cmbVade.SelectedItem.ToString().Replace(" gün", "").ToIntNN();
            else
                po.SetVadeNull();


            if (txtOdemeNotu.Text != "")
                po.OdemeNotu = txtOdemeNotu.Text;
            else
                po.SetOdemeNotuNull();

            po.StatusId = 1;

            po.SiparisTipi = SiparisTipi;

            if (po.POrderId < 0)
                dtMaster.Rows.Add(po);


            Data.TAM.POrderTableAdapter.Update(po);


            foreach (DataRow dr in dtLines.Rows)
                if (dr.RowState != DataRowState.Deleted)
                {
                    dr["POrderId"] = po.POrderId;
                    //dr["ETA"] = deETA.DateTime;
                }

            Data.TAM.POrderLinesTableAdapter.Update(dtLines);

            ShowReport();

            btnPrint.Enabled = true;

            //TODO : Artikeli de böyle yapabilirim !!!
            List<XForm> frms = AppSession.MainForm.GetFormOfType(typeof(Uretim.Siparisler));
            foreach (XForm x in frms)
                ((Uretim.Siparisler)x).RefreshData();

            if (POrderId < 0 && SiparisTipi == 2)
                AppSession.MainForm.ShowMdiChildForm(typeof(Aker.Uretim.SiparisTakipVeCikis), 2, po.POrderId);
        }

        private void ShowReport()
        {
            DataRowView dv = (DataRowView)gleMusteri.GetSelectedDataRow();
            string email = dv["Email"].ToStringNN();
            if (SiparisTipi == 1)
            {
                SiparisFormu report = new SiparisFormu(po.POrderId, po.LangId);
                AppSession.MainForm.ShowMdiChildForm(typeof(ReportViewer), report, email, "Sipariş No:" + po.POrderId);
            }
            else if (SiparisTipi == 2)
            {
                Iplik.SiparisFormu report = new Iplik.SiparisFormu(po.POrderId, po.LangId);
                AppSession.MainForm.ShowMdiChildForm(typeof(ReportViewer), report, email, "Sipariş No:" + po.POrderId);
            }
            //this.Close();          
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.DialogResult dr = XtraMessageBox.Show("Değişiklikler kaydedilsin mi?", "Uyarı", System.Windows.Forms.MessageBoxButtons.YesNo);
            if (dr == System.Windows.Forms.DialogResult.Yes)
                btnOrder.PerformClick();
            else
                ShowReport();
        }

        #region Add Product
        private void AddProductManual_Click(object sender, EventArgs e)
        {
            AddProduct adder = new AddProduct();
            adder.ProductSelected += adder_ProductSelected;
            adder.ShowDialog();
        }

        private void adder_ProductSelected(int productId, string artikel)
        {
            Orders_BarcodeRead(productId);
        }

        private void Orders_BarcodeRead(int BazProductId)
        {
            AkerDB.ProductRow product = Data.DB.Product.FindByProductId(BazProductId);
            if (product != null)
            {
                //if (dtLines.Select(string.Format("ProductId={0}", ProductId)).Length > 0)
                //    Console.Beep();
                //else
                {
                    AddProduct(BazProductId);
                    BestFit();
                    int rowHandle = gvLines.LocateByValue("BazProductId", BazProductId);
                    gvLines.MakeRowVisible(rowHandle);
                    gvLines.FocusedRowHandle = rowHandle;
                }
            }
        }

        private void AddProduct(int bazProductId)
        {
            AkerDB.POrderLinesRow pod = dtLines.NewPOrderLinesRow();
            pod.POrderId = po.POrderId;
            pod.BazProductId = bazProductId;
            pod.ETA = deETA.DateTime;
            dtLines.AddPOrderLinesRow(pod);
            FillProductDetail(pod);
        }

        #endregion

        private void DeleteOrderLines(object sender, EventArgs e)
        {
            List<int> ids = new List<int>();
            foreach (int rh in gvLines.GetSelectedRows())
            {
                int id = gvLines.GetRowCellValue(rh, "POrderLinesId").ToIntNN();
                if (id > 0)
                    ids.Add(id);
            }

            foreach (int id in ids)
                dtLines.Select("POrderLinesId=" + id.ToStringNN())[0].Delete();

            UpdateTotal();
        }

        private void cmbHafta_SelectedIndexChanged(object sender, EventArgs e)
        {
            int selectedIndex = cmbHafta.SelectedIndex;
            if (selectedIndex == 0)
                return;
            else if (selectedIndex < 11)
                deETA.EditValue = DateTime.Now.AddDays(7 * (selectedIndex));
            else if (selectedIndex == 11)
                deETA.EditValue = DateTime.Now.AddDays(10);
            else if (selectedIndex == 12)
                deETA.EditValue = DateTime.Now.AddDays(15);
        }



        private void gleMusteri_EditValueChanged(object sender, EventArgs e)
        {
            gleFaturaMusterisi.EditValue = gleTeslimatMusterisi.EditValue = gleMusteri.EditValue;
        }

        private void deETA_EditValueChanged(object sender, System.EventArgs e)
        {
            foreach (DataRow dr in dtLines.Rows)
                if (dr.RowState != DataRowState.Deleted)
                    dr["ETA"] = deETA.DateTime;
        }
    }
}
